<?php

/**
 * Created by PhpStorm.
 * User: earl
 * Date: 2017/6/3
 * Time: 下午1:43
 */
class Api_Demo extends PhalApi_Api
{

    private $demoDomain;

    public function __construct()
    {
        $this->demoDomain = new Domain_Demo();
    }

    public function getRules()
    {
        return array(
            'index' => array(
                'username' => array('name' => 'username', 'default' => 'PHPer',),
            ),
            'demoAdd' => array(
                'title' => array('name' => 'title', 'type' => 'string', 'require' => true, 'desc' => '标题'),
                'content' => array('name' => 'content', 'type' => 'string', 'require' => true, 'desc' => '内容'),
            ),
            'demoDel' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => 'id'),
            ),
            'addOpenID' => array(
                'openid' => array('name' => 'openid', 'type' => 'string', 'require' => true, 'desc' => 'openid'),
            ),
            'getTempMsg' => array(
                'fid' => array('name' => 'fid', 'type' => 'string', 'require' => true, 'desc' => 'formid'),
                'oid' => array('name' => 'oid', 'type' => 'string', 'require' => true, 'desc' => 'openid'),
            ),
            'wxPay' => array(
                'fid' => array('name' => 'fid', 'type' => 'string', 'require' => true, 'desc' => 'formid'),
                'oid' => array('name' => 'oid', 'type' => 'string', 'require' => true, 'desc' => 'openid'),
                'price' => array('name' => 'price', 'type' => 'float', 'require' => true, 'desc' => 'price'),
            ),

        );
    }

    /**
     * 默认接口服务
     * @return string title 标题
     * @return string content 内容
     * @return string version 版本，格式：X.X.X
     * @return int time 当前时间戳
     */
    public function index()
    {
        return array(
            'title' => 'Hello World!',
            'content' => T('Hi {name}, welcome to use PhalApi!', array('name' => $this->username)),
            'version' => PHALAPI_VERSION,
            'time' => $_SERVER['REQUEST_TIME'],
        );
    }

    /**
     * demo list
     * @return mixed
     */
    public function demoList()
    {
        return $this->demoDomain->demoList();
    }

    /**
     * demo Add
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    public function demoAdd()
    {
        return $this->demoDomain->demoAdd($this->title, $this->content);
    }

    /**
     * demo Del
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    public function demoDel()
    {
        return $this->demoDomain->demoDel($this->id);
    }

    /**
     * openid add
     * @return mixed
     */
    public function addOpenID()
    {
        return $this->demoDomain->addOpenID($this->openid);
    }


    /**
     * 上传文件
     * @throws PhalApi_Exception_BadRequest
     */
    public function uploadFile()
    {
        $oss_sdk_service = new OSS_Lite();
        $oss_sdk_service->set_debug_mode(FALSE);
        $bucket = "phalapi-applet";
        $filePath = $_FILES['file']['tmp_name'];
        $filename = sha1(uniqid(mt_rand(), 1)) . $_FILES['file']['name'];
        $response = $oss_sdk_service->upload_file_by_file($bucket, 'FILE/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time()) . '/' . $filename, $filePath);
        if ($response->status != 200) {
            throw new PhalApi_Exception_BadRequest(T('OSS ERROR'));
        }
        $temp = (array)($response);
        $url = $temp['header']['_info']['url'];

        return $this->demoDomain->addFiles($url);
    }

    /**
     * 获取小程序菊花码
     * 需要上线后才可以扫面进入，可带参数
     * @return string
     * @author Earl<guo@seosite.cn>
     */
    public function getCode()
    {
        $access_token = $this->getWxToken();

        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $post_data = array("path" => "pages/code/index", "width" => 300, "auto_color" => false, "line_color" => array("r" => "50", "g" => "250", "b" => "150"));

        $output = $this->curl_post($post_data, $url);

        file_put_contents("1.jpg", $output);

        $oss_sdk_service = new OSS_Lite();
        $oss_sdk_service->set_debug_mode(FALSE);
        $bucket = "phalapi-applet";
        $filePath = "./1.jpg";
        $filename = sha1(uniqid(mt_rand(), 1)) . "1.jpg";
        $response = $oss_sdk_service->upload_file_by_file($bucket, 'FILE/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time()) . '/' . $filename, $filePath);
        if ($response->status != 200) {
            throw new PhalApi_Exception_BadRequest(T('OSS ERROR'));
        }
        $temp = (array)($response);
        $url = $temp['header']['_info']['url'];
        unlink('1.jpg');
        return $this->demoDomain->addFiles($url);
    }

    /**
     * 发送模板信息
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    public function getTempMsg()
    {
        $access_token = $this->getWxToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $access_token;

        $post_data = array(
            'touser' => $this->oid,
            'template_id' => 'qu6rH94UMVegloy_07YDJgj5AnA1Sx1UXUi94JDX4Sw',
            'page' => 'pages/index/index',
            'form_id' => $this->fid,
            'data' => array(
                'keyword1' => array(
                    'value' => '201706071538',
                    'color' => '#EE7600'
                ),
                'keyword2' => array(
                    'value' => '测试数据',
                    'color' => '#FF0000'
                )
            ),
            'color' => '#000',
            'emphasis_keyword' => 'keyword1.DATA'
        );

        $ret = $this->curl_post($post_data, $url);

        return $ret;
    }

    /**
     * 微信支付
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    public function wxPay()
    {
        $mch_id = DI()->config->get('app.wxmini_mch_id');
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $post_tmp_data = array(
            'appid' => DI()->config->get('app.WechatMini.appid'),
            'mch_id' => $mch_id,
            'device_info' => 'WEB',
            'nonce_str' => md5(time()),
            'sign' => md5(time()),
            'sign_type' => 'MD5',
            'body' => '',
            'detail' => array(
                'goods_detail' => array(
                    0=>array(
                        'goods_id'=>time(),
                        'wxpay_goods_id'=>'',
                        'goods_name'=>'测试商品名称',
                        'quantity'=>1,
                        'price'=>100,
                        'goods_category'=>1,
                        'body'=>''
                    )
                )
            ),
            'attach' => '',
            'out_trade_no' => time(),
            'fee_type' => 'CNY',
            'total_fee' => 100,
            'spbill_create_ip' => '192.168.199.163',
            'time_start' => '',
            'time_expire' => '',
            'goods_tag' => '',
            'notify_url' => 'https://mb.800151.com/phalapi/Public/applet/?service=Demo.notify',
            'trade_type' => 'JSAPI',
            'limit_pay' => '',
            'openid' => '',
        );
        $post_data = $this->arrayToXml($post_tmp_data);

        var_dump($post_data);
        $ret = $this->curl_post($post_data,$url);

        return $ret;
    }

    public function notify()
    {
        exit('success');
    }


    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }


    /**
     * 获取微信token
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    private function getWxToken()
    {
        $wx_config = DI()->config->get('app.WechatMini');
        //1.获取access_token
        $ret = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wx_config['appid'] . '&secret=' . $wx_config['secret']);
        return json_decode($ret, true)['access_token'];
    }

    /**
     * curl_post
     * @param $post_data
     * @param $url
     * @return mixed
     * @author Earl<guo@seosite.cn>
     */
    private function curl_post($post_data, $url)
    {
        $en_post_data = json_encode($post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $en_post_data);
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

}
